<?php declare(strict_types = 1);


namespace App\Model\Logic;


use Swoft\Bean\Annotation\Mapping\Bean;

/**
 * @Bean()
 * Class AesLogic
 * @package App\Model\Logic
 */
class AesLogic
{

    protected $iv = '0a0203040f06070x';

    const METHOD = 'aes-256-cbc';

    /**
     * 通过AES加密请求数据
     *
     * @param array $query
     * @return string
     */
    public function AESEncryptRequest($encryptKey, $query){
        return $this->_encrypt_pass($query,$encryptKey);
    }

    // 加密
    private function _encrypt_pass($input, $key) {
        return base64_encode(openssl_encrypt($input, self::METHOD, $key, OPENSSL_RAW_DATA, $this->iv));
    }

    /**
     * 通过AES解密请求数据
     *
     * @param array $query
     * @return string
     */
    public function AESDecryptResponse($encryptKey,$data){
        return $this->_decrypt_pass($data,$encryptKey);
    }

    // 解密
    private function _decrypt_pass($sStr, $sKey) {
        $sStr = base64_decode($sStr);
        return openssl_decrypt($sStr, self::METHOD, $sKey, OPENSSL_RAW_DATA, $this->iv);
    }


    /**
     * 将PostId 加密后输出加密串
     * @param $post_id
     * @return string
     */
    public function aesPostToken($post_id, $member_id =  null)
    {
        $aes_key = config("app.aes_key");
        $data = [
            "pid" => $post_id
        ];

        if(!empty($member_id))
        {
            $data['mid'] = $member_id;
        }
        return $this->AESEncryptRequest($aes_key, json_encode($data));
    }

}